using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using JGSY.CourseManagement.Domain.Entities;
using JGSY.CourseManagement.Domain.Interfaces;
using JGSY.CourseManagement.Infrastructure.Data.EntityFramework;

namespace JGSY.CourseManagement.Infrastructure.Data.Repositories
{
    /// <summary>
    /// 用户仓储实现，处理用户数据访问
    /// </summary>
    public class UserRepository : IUserRepository
    {
        private readonly SessionDbContext _dbContext;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbContext">数据库上下文</param>
        public UserRepository(SessionDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        /// <summary>
        /// 根据用户名获取用户
        /// </summary>
        public async Task<User> GetByUserNameAsync(string userName)
        {
            return await _dbContext.Users.FirstOrDefaultAsync(u => u.UserName == userName);
        }

        /// <summary>
        /// 添加新用户
        /// </summary>
        public async Task AddAsync(User user)
        {
            await _dbContext.Users.AddAsync(user);
            await _dbContext.SaveChangesAsync();
        }

        /// <summary>
        /// 更新用户信息
        /// </summary>
        public async Task UpdateAsync(User user)
        {
            _dbContext.Entry(user).State = EntityState.Modified;
            await _dbContext.SaveChangesAsync();
        }

        /// <summary>
        /// 检查用户名是否已存在
        /// </summary>
        public async Task<bool> ExistsByUserNameAsync(string userName)
        {
            return await _dbContext.Users.AnyAsync(u => u.UserName == userName);
        }
    }
}